package com.arethusa;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumn;

import simpleorm.core.SConnection;
import simpleorm.core.SPreparedStatement;
import simpleorm.core.SResultSet;
import simpleorm.core.SValidationException;
import simpleorm.ui.SUIConstants;

import com.arethusa.langebaandb.Leeftijdsbepalingen;
import com.arethusa.langebaandb.Programma;
import com.arethusa.langebaandb.Programmanummers;
import com.arethusa.langebaandb.Start;
import com.arethusa.langebaandb.StartBean;
import com.arethusa.langebaandb.Vereniging;
import com.ibm.j2x.swing.util.TableUtilities;
import com.ibm.j2x.util.CollectionUtilities;

public class InvoerenStart extends JPanel implements SUIConstants {

	static final long serialVersionUID=1;
	private Integer depotNr = null;
	private String vereniging = "";
	private List<StartBean> starts;
	private Long currentID = null;
	private JComboBox verenigingComboBox = null;
	private JPanel verenigingPanel = null;
	private JLabel jLabel = null;
	private JScrollPane startsScrollPane = null;
	private JTable startsTable = null;
	private JPanel entryPanel = null;
	private JPanel invoerPanel = null;
	private JPanel startPanel = null;
	private JLabel jLabel1 = null;
	private JTextField startNrTextField = null;
	private JLabel jLabel2 = null;
	private JTextField naamTextField = null;
	private JLabel jLabel3 = null;
	private JComboBox programmaComboBox = null;
	private JPanel buttonPanel = null;
	private JButton voerinButton = null;
	private JButton wijzigButton = null;
	private JButton verwijderButton = null;
	private JLabel jLabel4 = null;
	private JTextField capNrTextField = null;
	private JPanel capNrPanel = null;
	private JCheckBox vastCheckBox = null;
	private JLabel jLabel6 = null;
	private JButton zoekButton = null;
	private ZoekVereniging zoekDialog = null;
	
	/**
	 * ActionListeners
	 */
	private class ProgrammaComboBoxActionListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
		}
		
	}
	private class StartNrTextFieldActionListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			// TODO StartNrTextFieldActionListener need to be implemented
			// Naam should be searched for in Starts and place in naamTextField
			System.out.println("StartNr is aangepast");
		}
		
	}
	private class VerenigingComboBoxActionListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
	        try {
				JComboBox cb = (JComboBox)arg0.getSource();
				String dnr = ((String)cb.getSelectedItem()).substring(0,5);
				depotNr = (dnr.equalsIgnoreCase("<Kies")?new Integer(0):new Integer(dnr));
				if( depotNr.intValue() != 0 ) {
					vereniging = ((String)cb.getSelectedItem()).substring(5).trim();
				}
				if(depotNr.intValue() != 0 ) {
					fillTable();
					clearInvoer();
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		
	}
	private class VoerinButtonActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			StartBean cur = new StartBean();
			cur.setId(new Long(0) );
			cur.setDepotnr(depotNr.toString());
			cur.setVereniging(vereniging);
			cur.setStartnr(startNrTextField.getText());
			cur.setNaam(naamTextField.getText());
			String prg = (String)programmaComboBox.getSelectedItem();
			cur.setPrognr(new Integer(prg.substring(0,2)));
			cur.setSuffix(getSuffix(cur.getPrognr(), cur.getStartnr()));
			cur.setVast(new Boolean(vastCheckBox.isSelected()));
			cur.setCapkleur(getCapKleur(cur.getPrognr(), cur.getVast()));
			try {
				if( ! capNrTextField.getText().equals("") ) {
						cur.setCapnr(new Integer(capNrTextField.getText()));
				} else {
					cur.setCapnr(findFirstFreeCapnr(cur.getPrognr()));
				}
				String msg = checkMaxAfstand(startNrTextField.getText(),
						cur.getPrognr());
				if( ! msg.equalsIgnoreCase("") ) {
					JOptionPane.showMessageDialog(null,	msg,
							"Validatie", JOptionPane.ERROR_MESSAGE);
				} else if( cur.getSuffix().length() == 0 ) {
					JOptionPane.showMessageDialog(null,	
							"Zwemmer mag gezien zijn leeftijd niet in dit programma starten.",
							"Validatie", JOptionPane.ERROR_MESSAGE);
				} else if( checkDuplicate(startNrTextField.getText(),
						cur.getPrognr()).longValue() != 0L ) {
					JOptionPane.showMessageDialog(null,	
							"Zwemmer mag niet twee keer in dit programma starten.",
							"Validatie", JOptionPane.ERROR_MESSAGE);
				} else {
					cur.create();
					fillTable();
					clearInvoer();
				}
			} catch (SValidationException e1) {
				JOptionPane.showMessageDialog(null,
					e1.getMessage(),
					"Validatie", JOptionPane.ERROR_MESSAGE);
			} catch (NumberFormatException e2) {
				JOptionPane.showMessageDialog(null,
					"CapNr moet een nummer zijn.",
					"Validatie", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	private class WijzigButtonActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			StartBean cur = new StartBean();
			cur.setId(currentID);
			cur.setDepotnr(depotNr.toString());
			cur.setVereniging(vereniging);
			cur.setStartnr(startNrTextField.getText());
			cur.setNaam(naamTextField.getText());
			String prg = (String)programmaComboBox.getSelectedItem();
			cur.setPrognr(new Integer(prg.substring(0,2)));
			cur.setSuffix(getSuffix(cur.getPrognr(), cur.getStartnr()));
			cur.setVast(new Boolean(vastCheckBox.isSelected()));
			cur.setCapkleur(getCapKleur(cur.getPrognr(), cur.getVast()));
			try {
				if( ! capNrTextField.getText().equals("") ) {
						cur.setCapnr(new Integer(capNrTextField.getText()));
				} else {
					cur.setCapnr(findFirstFreeCapnr(cur.getPrognr()));
				}
				boolean err = false;
				if( cur.getSuffix().length() == 0 ) {
					JOptionPane.showMessageDialog(null,	
						"Zwemmer mag gezien zijn leeftijd niet in dit programma starten.",
						"Validatie", JOptionPane.ERROR_MESSAGE);
					err = true;
				} 
				Long r = checkDuplicate(startNrTextField.getText(),
						cur.getPrognr());
				if( r.longValue() != 0 && r.longValue() != currentID.longValue()) {
					JOptionPane.showMessageDialog(null,	
							"Zwemmer mag niet twee keer in dit programma starten.",
							"Validatie", JOptionPane.ERROR_MESSAGE);
					err = true;
				} 
				if( !err ) {
					cur.update();
					fillTable();
					clearInvoer();
				}
			} catch (SValidationException e1) {
				JOptionPane.showMessageDialog(null,
					e1.getMessage(),
					"Validatie", JOptionPane.ERROR_MESSAGE);
			} catch (NumberFormatException e2) {
				JOptionPane.showMessageDialog(null,
					"CapNr moet een nummer zijn.",
					"Validatie", JOptionPane.ERROR_MESSAGE);
			}
		}
		
	}
	private class VerwijderButtonActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if(JOptionPane.showConfirmDialog(null,
					"Zeker weten?","Verwijderen",
					JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_CANCEL_OPTION ) return;
			StartBean cur = new StartBean();
			cur.setId(currentID);
			try {
				cur.delete();
		    	fillTable();
				clearInvoer();
			} catch (SValidationException e1) {
				JOptionPane.showMessageDialog(null,
						e1.getMessage(),
						"Validatie", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	private class TableSelectionListener implements ListSelectionListener {
	    public void valueChanged(ListSelectionEvent e) {
	        //Ignore extra messages.
	        if (e.getValueIsAdjusting()) return;

	        ListSelectionModel lsm = (ListSelectionModel)e.getSource();
	        if (lsm.isSelectionEmpty()) {
	            //no rows are selected
	        	getVoerinButton().setEnabled(true);
	        	getWijzigButton().setEnabled(false);
	        	getVerwijderButton().setEnabled(false);
	        } else {
	            int selectedRow = lsm.getMinSelectionIndex();
	            //selectedRow is selected
	        	getVoerinButton().setEnabled(true);
	        	getWijzigButton().setEnabled(true);
	        	getVerwijderButton().setEnabled(true);
	        	StartBean r = (StartBean)starts.get(selectedRow);
	        	currentID = r.getId();
	        	getNaamTextField().setText(r.getNaam());
	        	getStartNrTextField().setText(r.getStartnr());
	        	getProgrammaComboBox().setSelectedIndex(r.getPrognr().intValue());
	    		getCapNrTextField().setText(r.getCapnr().toString());
	    		getVastCheckBox().setSelected(r.getVast().booleanValue());
	        }
	    }
	}
	/**
	 * This is the default constructor
	 */
	public InvoerenStart() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setLayout(new BorderLayout());
		this.setSize(399, 456);
		this.add(getEntryPanel(), java.awt.BorderLayout.CENTER);
		this.add(getVerenigingPanel(), java.awt.BorderLayout.NORTH);
		zoekDialog = new ZoekVereniging();
	}

	/**
	 * This method initializes jVerenigingComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getVerenigingComboBox() {
		if (verenigingComboBox == null) {
			verenigingComboBox = new JComboBox();
			verenigingComboBox.setEditable(true);
			verenigingComboBox.addActionListener(new VerenigingComboBoxActionListener());
//			SConnection.begin();
			SPreparedStatement stmt = Vereniging.meta.select(
					"1=1", "DepotNr");
			SResultSet res = stmt.execute();
			verenigingComboBox .addItem("<Kies vereniging>");
			while (res.hasNext()) {
				Vereniging ver = (Vereniging)res.getRecord();
				int dnr = ver.get_fldDepotnr().intValue();
				verenigingComboBox .addItem(
						(dnr<10000?"0":"")+dnr+" "+ver.get_fldNaam());
			}
//			SConnection.commit();
		}
		return verenigingComboBox;
	}

	/**
	 * This method initializes jVerenigingPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getVerenigingPanel() {
		if (verenigingPanel == null) {
			FlowLayout flowLayout = new FlowLayout();
			flowLayout.setAlignment(java.awt.FlowLayout.LEFT);
			jLabel = new JLabel();
			jLabel.setText("Vereniging");
			verenigingPanel = new JPanel();
			verenigingPanel.setLayout(flowLayout);
			verenigingPanel.setComponentOrientation(java.awt.ComponentOrientation.LEFT_TO_RIGHT);
			verenigingPanel.add(jLabel, null);
			verenigingPanel.add(getVerenigingComboBox(), null);
			verenigingPanel.add(getZoekButton(), null);
		}
		return verenigingPanel;
	}

	/**
	 * This method initializes jStartsScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getStartsScrollPane() {
		if (startsScrollPane == null) {
			startsScrollPane = new JScrollPane();
			startsScrollPane.setViewportView(getStartsTable());
		}
		return startsScrollPane;
	}

	/**
	 * This method initializes jStartsTable	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getStartsTable() {
		if (startsTable == null) {
			startsTable = new JTable();
			startsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
			startsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			startsTable.setShowGrid(true);
//			Ask to be notified of selection changes.
			startsTable.getSelectionModel().addListSelectionListener(new TableSelectionListener());
		}
		return startsTable;
	}

	/**
	 * This method initializes jEntryPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getEntryPanel() {
		if (entryPanel == null) {
			entryPanel = new JPanel();
			entryPanel.setLayout(new BorderLayout());
			entryPanel.add(getStartsScrollPane(), java.awt.BorderLayout.CENTER);
			entryPanel.add(getInvoerPanel(), java.awt.BorderLayout.NORTH);
		}
		return entryPanel;
	}

	/**
	 * This method initializes jInvoerPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getInvoerPanel() {
		if (invoerPanel == null) {
			invoerPanel = new JPanel();
			invoerPanel.setLayout(new BorderLayout());
			invoerPanel.add(getStartPanel(), java.awt.BorderLayout.WEST);
			invoerPanel.add(getButtonPanel(), java.awt.BorderLayout.CENTER);
		}
		return invoerPanel;
	}

	/**
	 * This method initializes jStartPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getStartPanel() {
		if (startPanel == null) {
			GridBagConstraints gridBagConstraints41 = new GridBagConstraints();
			gridBagConstraints41.gridx = 1;
			gridBagConstraints41.anchor = java.awt.GridBagConstraints.WEST;
			gridBagConstraints41.fill = java.awt.GridBagConstraints.VERTICAL;
			gridBagConstraints41.gridy = 3;
			GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.gridx = 0;
			gridBagConstraints11.anchor = java.awt.GridBagConstraints.EAST;
			gridBagConstraints11.insets = new java.awt.Insets(0,5,0,5);
			gridBagConstraints11.ipadx = 0;
			gridBagConstraints11.ipady = 9;
			gridBagConstraints11.gridy = 3;
			jLabel4 = new JLabel();
			jLabel4.setText("CapNr");
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.fill = java.awt.GridBagConstraints.NONE;
			gridBagConstraints5.gridy = 2;
			gridBagConstraints5.ipadx = 0;
			gridBagConstraints5.weightx = 1.0;
			gridBagConstraints5.gridwidth = 1;
			gridBagConstraints5.anchor = java.awt.GridBagConstraints.WEST;
			gridBagConstraints5.gridheight = 1;
			gridBagConstraints5.gridx = 1;
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.gridx = 0;
			gridBagConstraints4.ipadx = 70;
			gridBagConstraints4.ipady = 9;
			gridBagConstraints4.insets = new java.awt.Insets(0,5,0,5);
			gridBagConstraints4.anchor = java.awt.GridBagConstraints.EAST;
			gridBagConstraints4.gridy = 2;
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.fill = java.awt.GridBagConstraints.NONE;
			gridBagConstraints3.gridy = 1;
			gridBagConstraints3.ipadx = 200;
			gridBagConstraints3.ipady = 5;
			gridBagConstraints3.weightx = 1.0;
			gridBagConstraints3.anchor = java.awt.GridBagConstraints.WEST;
			gridBagConstraints3.gridx = 1;
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.gridx = 0;
			gridBagConstraints2.ipadx = 50;
			gridBagConstraints2.ipady = 9;
			gridBagConstraints2.insets = new java.awt.Insets(0,5,0,5);
			gridBagConstraints2.anchor = java.awt.GridBagConstraints.EAST;
			gridBagConstraints2.gridy = 1;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.fill = java.awt.GridBagConstraints.NONE;
			gridBagConstraints1.gridy = 0;
			gridBagConstraints1.ipadx = 70;
			gridBagConstraints1.ipady = 5;
			gridBagConstraints1.weightx = 1.0;
			gridBagConstraints1.insets = new java.awt.Insets(0,0,0,0);
			gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST;
			gridBagConstraints1.gridx = 1;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 0;
			gridBagConstraints.ipadx = 10;
			gridBagConstraints.ipady = 9;
			gridBagConstraints.insets = new java.awt.Insets(0,5,0,5);
			gridBagConstraints.weightx = 3.0D;
			gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
			gridBagConstraints.gridy = 0;
			jLabel3 = new JLabel();
			jLabel3.setText("Programma");
			jLabel3.setComponentOrientation(java.awt.ComponentOrientation.RIGHT_TO_LEFT);
			jLabel3.setPreferredSize(new java.awt.Dimension(20,16));
			jLabel3.setName("jLabel3");
			jLabel2 = new JLabel();
			jLabel2.setText("Naam");
			jLabel2.setComponentOrientation(java.awt.ComponentOrientation.RIGHT_TO_LEFT);
			jLabel2.setName("jLabel2");
			jLabel1 = new JLabel();
			jLabel1.setText("Startnummer");
			jLabel1.setComponentOrientation(java.awt.ComponentOrientation.RIGHT_TO_LEFT);
			jLabel1.setName("jLabel1");
			startPanel = new JPanel();
			startPanel.setLayout(new GridBagLayout());
			startPanel.add(jLabel1, gridBagConstraints);
			startPanel.add(getStartNrTextField(), gridBagConstraints1);
			startPanel.add(jLabel2, gridBagConstraints2);
			startPanel.add(getNaamTextField(), gridBagConstraints3);
			startPanel.add(jLabel3, gridBagConstraints4);
			startPanel.add(getProgrammaComboBox(), gridBagConstraints5);
			startPanel.add(jLabel4, gridBagConstraints11);
			startPanel.add(getCapNrPanel(), gridBagConstraints41);
		}
		return startPanel;
	}

	/**
	 * This method initializes jStartNrTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getStartNrTextField() {
		if (startNrTextField == null) {
			startNrTextField = new JTextField();
			startNrTextField.setName("jStartNrTextField");
			startNrTextField.addActionListener(new StartNrTextFieldActionListener());
		}
		return startNrTextField;
	}

	/**
	 * This method initializes jNaamTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getNaamTextField() {
		if (naamTextField == null) {
			naamTextField = new JTextField();
			naamTextField.setName("jNaamTextField");
		}
		return naamTextField;
	}

	/**
	 * This method initializes jProgrammaComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getProgrammaComboBox() {
		if (programmaComboBox == null) {
			programmaComboBox = new JComboBox();
			programmaComboBox.setComponentOrientation(java.awt.ComponentOrientation.UNKNOWN);
			programmaComboBox.addActionListener(new ProgrammaComboBoxActionListener());
//			SConnection.begin();
			SPreparedStatement stmt = Programmanummers.meta.select(
					"1=1", "ProgNr");
			SResultSet res = stmt.execute();
			programmaComboBox .addItem("<Kies programma>");
			while (res.hasNext()) {
				Programmanummers prg = (Programmanummers)res.getRecord();
				int pnr = prg.get_fldPrognr().intValue();
				programmaComboBox .addItem(
						(pnr<10?"0":"")+pnr+" "+prg.get_fldTitel());
			}
//			SConnection.commit();
		}
		return programmaComboBox;
	}

	/**
	 * This method initializes jButtonPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getButtonPanel() {
		if (buttonPanel == null) {
			buttonPanel = new JPanel();
			buttonPanel.setLayout(new BoxLayout(getButtonPanel(), BoxLayout.Y_AXIS));
			buttonPanel.add(getVoerinButton(), null);
			buttonPanel.add(getWijzigButton(), null);
			buttonPanel.add(getVerwijderButton(), null);
		}
		return buttonPanel;
	}

	/**
	 * This method initializes jVoerinButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getVoerinButton() {
		if (voerinButton == null) {
			voerinButton = new JButton();
			voerinButton.setText("Voer in");
			voerinButton.setPreferredSize(new java.awt.Dimension(74,20));
			voerinButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
			voerinButton.addActionListener(new VoerinButtonActionListener());
		}
		return voerinButton;
	}

	/**
	 * This method initializes WijzigButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getWijzigButton() {
		if (wijzigButton == null) {
			wijzigButton = new JButton();
			wijzigButton.setText("Wijzig");
			wijzigButton.setPreferredSize(new java.awt.Dimension(70,20));
			wijzigButton.setEnabled(false);
			wijzigButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
			wijzigButton.addActionListener(new WijzigButtonActionListener());
		}
		return wijzigButton;
	}

	/**
	 * This method initializes verwijderButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getVerwijderButton() {
		if (verwijderButton == null) {
			verwijderButton = new JButton();
			verwijderButton.setText("Verwijder");
			verwijderButton.setPreferredSize(new java.awt.Dimension(89,20));
			verwijderButton.setEnabled(false);
			verwijderButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
			verwijderButton.addActionListener(new VerwijderButtonActionListener());
		}
		return verwijderButton;
	}

	/**
	 * This method initializes capNrPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getCapNrPanel() {
		if (capNrPanel == null) {
			jLabel6 = new JLabel();
			jLabel6.setText("Vaste cap");
			jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
			jLabel6.setPreferredSize(new java.awt.Dimension(80,16));
			capNrPanel = new JPanel();
			capNrPanel.setLayout(new BoxLayout(getCapNrPanel(), BoxLayout.X_AXIS));
			capNrPanel.add(getCapNrTextField(), null);
			capNrPanel.add(jLabel6, null);
			capNrPanel.add(getVastCheckBox(), null);
		}
		return capNrPanel;
	}
	
	/**
	 * This method initializes capNrTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getCapNrTextField() {
		if (capNrTextField == null) {
			capNrTextField = new JTextField();
			capNrTextField.setPreferredSize(new java.awt.Dimension(25,20));
			capNrTextField.setHorizontalAlignment(javax.swing.JTextField.LEFT);
		}
		return capNrTextField;
	}

	/**
	 * This method initializes vastCheckBox	
	 * 	
	 * @return javax.swing.JCheckBox	
	 */
	private JCheckBox getVastCheckBox() {
		if (vastCheckBox == null) {
			vastCheckBox = new JCheckBox();
		}
		return vastCheckBox;
	}
	/*
	 * ========================================================================
	 */
	@SuppressWarnings("unchecked")
	private void fillTable() {
		List<StartBean> tmp = new ArrayList<StartBean>();
		/// Prepare and execute the query
		if( depotNr.intValue() > 0 ) {
			boolean hasBegun = SConnection.getConnection().hasBegun();
			if( ! hasBegun ) { SConnection.begin(); }
			SPreparedStatement stmt = Start.meta.select(
					"DepotNr="+depotNr, "ProgNr,Naam");
			SResultSet res = stmt.execute();
			
			/// loop through the results
			while (res.hasNext()) {
				StartBean strt = new StartBean(((Start)res.getRecord()));
				tmp.add(strt);
			}
	    	SConnection.commit();
	    	starts = CollectionUtilities.observableList(tmp);
			TableUtilities.setViewToModel("LangebaanModel.xml", "StartEntry", getStartsTable(), starts);
			TableColumn col1 = getStartsTable().getColumnModel().getColumn(0);
			col1.setMaxWidth(20);
			TableColumn col2 = getStartsTable().getColumnModel().getColumn(1);
			col2.setMaxWidth(10);
			TableColumn col3 = getStartsTable().getColumnModel().getColumn(2);
			col3.setMaxWidth(70);
			TableColumn col4 = getStartsTable().getColumnModel().getColumn(3);
			col4.setPreferredWidth(200);
			TableColumn col5 = getStartsTable().getColumnModel().getColumn(4);
			col5.setMaxWidth(50);
			TableColumn col6 = getStartsTable().getColumnModel().getColumn(5);
			col6.setMaxWidth(30);
			TableColumn col7 = getStartsTable().getColumnModel().getColumn(6);
			col7.setMaxWidth(40);
		}
	}
	
	private void clearInvoer() {
		getStartNrTextField().setText(null);
		getNaamTextField().setText(null);
		getProgrammaComboBox().setSelectedIndex(0);
		getCapNrTextField().setText(null);
		getVastCheckBox().setSelected(false);
	}

	private String getSuffix(Integer progNr, String startNr) {
		String sfx = "";
		int lft = new Integer(startNr.substring(0,2)).intValue();
		Calendar rightNow = Calendar.getInstance();
		lft = rightNow.get(Calendar.YEAR) - 1900 - lft;		// leeftijd van zwemmer
		lft = lft>100?lft-100:lft;
		boolean hasBegun = SConnection.getConnection().hasBegun();
		if( ! hasBegun ) { SConnection.begin(); }
		Connection JDBCcon = SConnection.getBegunDBConnection();
		try {
			Statement stmt = JDBCcon.createStatement();
			ResultSet res = stmt.executeQuery("SELECT a.sex, a.suffix, b.van, c.tem FROM " +
					"(programma AS a INNER JOIN categorie AS b ON a.LeeftijdVan=b.cat " +
					"INNER JOIN categorie AS c ON a.LeeftijdTM=c.cat)" +
					" WHERE ProgNr="+ progNr.toString());
			while( res.next() ) {
				if( lft>=res.getInt("van") && lft<=res.getInt("tem") ) {
					sfx = res.getString("suffix");
					break;
				}
			}
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					e.getMessage()+e.getCause(),
					"SQL fout", JOptionPane.ERROR_MESSAGE);
		}
		if( ! hasBegun ) { SConnection.commit(); }
		return sfx;
	}
	
	private String getCapKleur (Integer progNr, Boolean vast) {
		String ckl = "";
		boolean hasBegun = SConnection.getConnection().hasBegun();
		if( ! hasBegun ) { SConnection.begin(); }
		SPreparedStatement stmt = Programma.meta.select(   
				"PROGNR="+ progNr.toString(),"SUFFIX");
		SResultSet res = stmt.execute();
		res.hasNext();
		Programma prg = (Programma)res.getRecord();
		if( vast.booleanValue() ) { ckl = prg.get_fldCapkleurknzb(); }
		else { ckl = prg.get_fldCapkleur(); }
		if( ! hasBegun ) { SConnection.commit(); }
		return ckl;
	}
	
	private Integer findFirstFreeCapnr(Integer progNr) {
		int cnr = 0;
		boolean hasBegun = SConnection.getConnection().hasBegun();
		if( ! hasBegun ) { SConnection.begin(); }
		SPreparedStatement stmt = Start.meta.select(   
				"PROGNR="+ progNr.toString(),"CAPNR");
		SResultSet res = stmt.execute();
		int prvcnr = 0;
		while( res.hasNext() ) {
			Start strt = (Start)res.getRecord();
			if( (strt.get_fldCapnr().intValue() - prvcnr) > 1 ) {
				cnr = prvcnr + 1;
				break;
			} else { 
				prvcnr = strt.get_fldCapnr().intValue();
			}
		}
		if( ! hasBegun ) { SConnection.commit(); }
		return new Integer(cnr);
	}
	
	private Integer getProgrammaAfstand(Integer progNr) {
		Integer af;
		boolean hasBegun = SConnection.getConnection().hasBegun();
		if( ! hasBegun ) { SConnection.begin(); }
		SPreparedStatement stmt = Programma.meta.select(   
				"PROGNR="+ progNr.toString(),"SUFFIX");
		SResultSet res = stmt.execute();
		res.hasNext();
		Programma prg = (Programma)res.getRecord();
		af = prg.get_fldAfstand();
		if( ! hasBegun ) { SConnection.commit(); }
		return af;
	}

	private String checkMaxAfstand(String startNr, Integer progNr) {
		boolean hasBegun = SConnection.getConnection().hasBegun();
		if( ! hasBegun ) { SConnection.begin(); }
		SPreparedStatement stmt = Start.meta.select(   
				"STARTNR='"+ startNr+"'","PROGNR");
		SResultSet res = stmt.execute();
		int sumAfstand = getProgrammaAfstand(progNr).intValue();
		int sumStarts = 1;
		while( res.hasNext() ) {
			sumStarts += 1;
			Start strt = (Start)res.getRecord();
			sumAfstand += getProgrammaAfstand(strt.get_fldPrognr()).intValue();
		}
		
		int lft = new Integer(startNr.substring(0,2)).intValue();		// leeftijd van zwemmer
		Calendar rightNow = Calendar.getInstance();
		lft = rightNow.get(Calendar.YEAR) - 1900 - lft;
		lft = lft>100?lft-100:lft;
		
		stmt = Leeftijdsbepalingen.meta.select(   
				"LEEFTIJD='"+ new Integer(lft).toString()+"'","LEEFTIJD");
		res = stmt.execute();
		if( res.hasNext() ) {
			Leeftijdsbepalingen lftb = (Leeftijdsbepalingen)res.getRecord();
			int maxAfstand = lftb.get_fldMaxafstand().intValue();
			int maxStarts = lftb.get_fldMaxstarts().intValue();
			if( ! hasBegun ) SConnection.commit();
			if( sumAfstand > maxAfstand ) {
				return "Zwemmer zwemt nu "+new Integer(sumAfstand).toString()+" m en mag maar "
				+ new Integer(maxAfstand).toString()+" m zwemmen.";
			}
			if( sumStarts > maxStarts ) {
				return "Zwemmer start nu "+new Integer(sumStarts).toString()+" keer en mag maar "
				+new Integer(maxStarts).toString()+" keer starten.";
			}
		} else {
			if( ! hasBegun ) SConnection.commit();
			if( lft < 6 ) {
				return "Zwemmer is jonger dan 6 jaar.";
			}
		}
		return "";
	}

	private Long checkDuplicate(String startNr, Integer progNr) {
		Long id = new Long(0);
		boolean hasBegun = SConnection.getConnection().hasBegun();
		if( ! hasBegun ) { SConnection.begin(); }
		SPreparedStatement stmt = Start.meta.select(   
				"STARTNR='"+ startNr+"' AND PROGNR="+progNr,"PROGNR");
		SResultSet res = stmt.execute();
		if( res.hasNext() ){
			Start strt = (Start)res.getRecord();
			id = strt.get_fldId();
		}
		if( ! hasBegun ) SConnection.commit();
		return id;
	}
		
	/**
	 * This method initializes zoekButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getZoekButton() {
		if (zoekButton == null) {
			zoekButton = new JButton();
			zoekButton.setText("Zoek");
			zoekButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					zoekDialog.clear();
					zoekDialog.setVisible(true);
					verenigingComboBox.setSelectedItem(zoekDialog.getSelectedDepotnr());
				}
			});
		}
		return zoekButton;
	}
	
}  //  @jve:decl-index=0:visual-constraint="10,10"
